#!/bin/bash

# Feng Admin 项目启动脚本 (Linux/macOS)
# 用于同时启动前端和后端服务

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 清屏
clear

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Feng Admin - 启动脚本 (Linux/macOS)${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 检查项目根目录
if [ ! -d "apps/backend" ] || [ ! -d "apps/frontend" ]; then
    echo -e "${RED}错误: 请在项目根目录下运行此脚本${NC}"
    echo ""
    echo "当前目录: $(pwd)"
    echo "期望目录结构:"
    echo "  Feng_Admin/"
    echo "    ├── apps/"
    echo "    │   ├── backend/"
    echo "    │   └── frontend/"
    echo ""
    read -p "按回车键退出..."
    exit 1
fi

# 函数: 检查Python是否安装
check_python() {
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
        echo -e "${GREEN}✓ Python3 已安装${NC}"
        return 0
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
        echo -e "${GREEN}✓ Python 已安装${NC}"
        return 0
    else
        echo -e "${RED}✗ Python 未安装${NC}"
        echo "请先安装 Python 3.8+"
        return 1
    fi
}

# 函数: 检查Node.js是否安装
check_node() {
    if command -v node &> /dev/null; then
        echo -e "${GREEN}✓ Node.js 已安装 ($(node -v))${NC}"
        return 0
    else
        echo -e "${RED}✗ Node.js 未安装${NC}"
        echo "请先安装 Node.js 16+"
        return 1
    fi
}

# 函数: 检查npm是否安装
check_npm() {
    if command -v npm &> /dev/null; then
        echo -e "${GREEN}✓ npm 已安装 ($(npm -v))${NC}"
        return 0
    else
        echo -e "${RED}✗ npm 未安装${NC}"
        return 1
    fi
}

# 环境检查
echo -e "${BLUE}正在检查环境...${NC}"
echo ""

if ! check_python; then
    read -p "按回车键退出..."
    exit 1
fi

if ! check_node; then
    read -p "按回车键退出..."
    exit 1
fi

if ! check_npm; then
    read -p "按回车键退出..."
    exit 1
fi

echo ""

# 环境配置检查
echo -e "${BLUE}检查环境配置...${NC}"
echo ""

# 函数: 检查端口是否被占用
check_port() {
    local port=$1
    if command -v lsof &> /dev/null; then
        lsof -i :$port > /dev/null 2>&1
        return $?
    elif command -v ss &> /dev/null; then
        ss -tuln | grep ":$port " > /dev/null 2>&1
        return $?
    elif command -v netstat &> /dev/null; then
        netstat -tuln | grep ":$port " > /dev/null 2>&1
        return $?
    else
        # 无法检测，假设可用
        return 1
    fi
}

# 函数: 获取可用端口
get_available_port() {
    local start_port=$1
    local port=$start_port
    
    while check_port $port; do
        port=$((port + 1))
        if [ $port -gt 65535 ]; then
            echo "0"
            return
        fi
    done
    
    echo "$port"
}

# 函数: 验证端口号
validate_port() {
    local port=$1
    if [[ ! "$port" =~ ^[0-9]+$ ]]; then
        return 1
    fi
    if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
        return 1
    fi
    return 0
}

# 函数: 安全切换目录
safe_cd() {
    local target_dir=$1
    if [ ! -d "$target_dir" ]; then
        echo -e "${RED}错误: 目录 $target_dir 不存在${NC}"
        return 1
    fi
    cd "$target_dir" || {
        echo -e "${RED}错误: 无法切换到目录 $target_dir${NC}"
        return 1
    }
    return 0
}

# 函数: 设置.env文件权限
set_env_permissions() {
    local env_file=$1
    if [ -f "$env_file" ]; then
        chmod 600 "$env_file"
        echo -e "${GREEN}✓ 已设置 $env_file 权限为 600 (仅所有者可读写)${NC}"
    fi
}

# 函数: 快速配置环境
quick_setup_env() {
    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  快速环境配置${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    
    # 后端配置
    echo -e "${YELLOW}[1/2] 后端配置${NC}"
    echo ""
    
    # 生成密钥
    echo "正在生成安全密钥..."
    SECRET_KEY=$($PYTHON_CMD -c "import secrets; print(secrets.token_hex(32))" 2>/dev/null || echo "dev-secret-key-$(date +%s)")
    JWT_SECRET_KEY=$($PYTHON_CMD -c "import secrets; print(secrets.token_hex(32))" 2>/dev/null || echo "jwt-secret-key-$(date +%s)")
    
    # 询问是否远程访问
    read -p "是否需要配置远程访问? (y/N): " remote_access
    
    if [[ $remote_access =~ ^[Yy]$ ]]; then
        echo ""
        echo "请输入服务器域名或IP地址（如: yourwebsite.net 或 192.168.1.100）"
        read -p "域名/IP: " server_addr
        
        echo ""
        echo "请输入前端端口（直接回车使用 5173）"
        while true; do
            read -p "前端端口 [5173]: " frontend_port
            frontend_port=${frontend_port:-5173}
            if validate_port "$frontend_port"; then
                break
            else
                echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
            fi
        done
        
        # 检查前端端口是否被占用
        if check_port $frontend_port; then
            echo -e "${YELLOW}⚠️  端口 $frontend_port 已被占用${NC}"
            available_port=$(get_available_port $frontend_port)
            if [ "$available_port" != "0" ]; then
                read -p "使用可用端口 $available_port ? (Y/n): " use_available
                if [[ ! $use_available =~ ^[Nn]$ ]]; then
                    frontend_port=$available_port
                else
                    while true; do
                        read -p "请输入其他端口: " frontend_port
                        if validate_port "$frontend_port"; then
                            break
                        else
                            echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                        fi
                    done
                fi
            else
                read -p "请输入其他端口: " frontend_port
            fi
        fi
        
        echo ""
        echo "请输入后端端口（直接回车使用 5001）"
        while true; do
            read -p "后端端口 [5001]: " backend_port
            backend_port=${backend_port:-5001}
            if validate_port "$backend_port"; then
                break
            else
                echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
            fi
        done
        
        # 检查后端端口是否被占用
        if check_port $backend_port; then
            echo -e "${YELLOW}⚠️  端口 $backend_port 已被占用${NC}"
            available_port=$(get_available_port $backend_port)
            if [ "$available_port" != "0" ]; then
                read -p "使用可用端口 $available_port ? (Y/n): " use_available
                if [[ ! $use_available =~ ^[Nn]$ ]]; then
                    backend_port=$available_port
                else
                    while true; do
                        read -p "请输入其他端口: " backend_port
                        if validate_port "$backend_port"; then
                            break
                        else
                            echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                        fi
                    done
                fi
            else
                while true; do
                    read -p "请输入其他端口: " backend_port
                    if validate_port "$backend_port"; then
                        break
                    else
                        echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                    fi
                done
            fi
        fi
        
        echo ""
        echo "请选择协议:"
        echo "  1. HTTP"
        echo "  2. HTTPS"
        read -p "请选择 (1-2) [1]: " protocol_choice
        if [ "$protocol_choice" = "2" ]; then
            protocol="https"
        else
            protocol="http"
        fi
        
        API_URL="${protocol}://${server_addr}:${backend_port}"
        CORS_ORIGIN="${protocol}://${server_addr}:${frontend_port}"
    else
        # 本地开发模式，也检查端口
        backend_port=5001
        frontend_port=5173
        
        # 检查并处理后端端口
        if check_port $backend_port; then
            echo -e "${YELLOW}⚠️  后端端口 $backend_port 已被占用${NC}"
            available_port=$(get_available_port $backend_port)
            if [ "$available_port" != "0" ] && [ "$available_port" != "$backend_port" ]; then
                echo "将使用可用端口: $available_port"
                backend_port=$available_port
            fi
        fi
        
        # 检查并处理前端端口
        if check_port $frontend_port; then
            echo -e "${YELLOW}⚠️  前端端口 $frontend_port 已被占用${NC}"
            available_port=$(get_available_port $frontend_port)
            if [ "$available_port" != "0" ] && [ "$available_port" != "$frontend_port" ]; then
                echo "将使用可用端口: $available_port"
                frontend_port=$available_port
            fi
        fi
        
        API_URL="http://localhost:${backend_port}"
        CORS_ORIGIN="http://localhost:${frontend_port}"
    fi
    
    # 创建后端 .env
    cat > apps/backend/.env << EOF
# Feng Admin 后端环境配置
# 快速配置生成于 $(date)

FLASK_ENV=development
FLASK_DEBUG=True
SECRET_KEY=${SECRET_KEY}
JWT_SECRET_KEY=${JWT_SECRET_KEY}
JWT_ACCESS_TOKEN_EXPIRES=24
JWT_REFRESH_TOKEN_EXPIRES=30
CORS_ORIGINS=${CORS_ORIGIN}
GITHUB_TRENDING_CACHE_HOURS=4
LOG_LEVEL=INFO
FLASK_HOST=0.0.0.0
FLASK_PORT=${backend_port}
EOF
    
    # 设置后端.env文件权限
    set_env_permissions "apps/backend/.env"
    echo -e "${GREEN}✓ 后端配置已创建${NC}"
    
    # 前端配置
    echo ""
    echo -e "${YELLOW}[2/2] 前端配置${NC}"
    
    # 根据是否远程访问决定主机访问策略
    if [[ $remote_access =~ ^[Yy]$ ]]; then
        # 远程访问：使用域名白名单（更安全）
        cat > apps/frontend/.env << EOF
# Feng Admin 前端环境配置
# 快速配置生成于 $(date)

VITE_API_BASE_URL=${API_URL}
VITE_SERVER_HOST=0.0.0.0
VITE_SERVER_PORT=${frontend_port}
VITE_APP_TITLE=Feng Admin
VITE_APP_VERSION=1.0.0
VITE_ENABLE_DEV_TOOLS=true
VITE_ENABLE_LOGGING=true
# 远程访问模式：仅允许配置的域名
VITE_ALLOWED_HOSTS=${server_addr}
EOF
        # 设置前端.env文件权限
        set_env_permissions "apps/frontend/.env"
    else
        # 本地开发：允许所有主机（方便开发）
        cat > apps/frontend/.env << EOF
# Feng Admin 前端环境配置
# 快速配置生成于 $(date)

VITE_API_BASE_URL=${API_URL}
VITE_SERVER_HOST=0.0.0.0
VITE_SERVER_PORT=${frontend_port}
VITE_APP_TITLE=Feng Admin
VITE_APP_VERSION=1.0.0
VITE_ENABLE_DEV_TOOLS=true
VITE_ENABLE_LOGGING=true
# 本地开发模式：允许所有主机访问
VITE_ALLOW_ALL_HOSTS=true
EOF
        # 设置前端.env文件权限
        set_env_permissions "apps/frontend/.env"
    fi
    
    echo -e "${GREEN}✓ 前端配置已创建${NC}"
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  配置完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    if [[ $remote_access =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}配置信息:${NC}"
        echo -e "  服务器地址: ${CYAN}${server_addr}${NC}"
        echo -e "  前端地址: ${CYAN}${CORS_ORIGIN}${NC}"
        echo -e "  后端地址: ${CYAN}${API_URL}${NC}"
        echo -e "  ${GREEN}✓ 已配置域名白名单，仅允许 ${server_addr} 访问${NC}"
        echo ""
    fi
}

# 检查后端 .env 文件
if [ ! -f "apps/backend/.env" ]; then
    echo -e "${YELLOW}⚠️  未检测到后端环境配置文件${NC}"
    echo ""
    echo "请选择配置方式:"
    echo "  1. 快速配置 (推荐)"
    echo "  2. 完整向导"
    echo "  3. 跳过配置 (使用默认值)"
    echo ""
    read -p "请选择 (1-3) [1]: " config_choice
    config_choice=${config_choice:-1}
    
    case $config_choice in
        1)
            quick_setup_env
            ;;
        2)
            if [ -f "scripts/setup-env.sh" ]; then
                chmod +x scripts/setup-env.sh
                ./scripts/setup-env.sh
            else
                echo -e "${RED}错误: 找不到配置向导脚本${NC}"
                echo -e "${YELLOW}使用快速配置代替...${NC}"
                quick_setup_env
            fi
            ;;
        3)
            echo -e "${YELLOW}将使用默认配置继续...${NC}"
            ;;
        *)
            echo -e "${YELLOW}无效选项，使用快速配置...${NC}"
            quick_setup_env
            ;;
    esac
    echo ""
else
    echo -e "${GREEN}✓ 后端环境配置已就绪${NC}"
fi

# 检查前端 .env 文件
if [ ! -f "apps/frontend/.env" ]; then
    echo -e "${YELLOW}⚠️  未检测到前端环境配置文件${NC}"
    
    # 如果后端配置也不存在，已经在上面的配置中一起创建了
    if [ ! -f "apps/backend/.env" ]; then
        echo -e "${YELLOW}前端配置将在后端配置时一起创建${NC}"
    else
        # 后端配置存在但前端不存在，询问用户
        echo ""
        read -p "是否需要配置前端环境? (Y/n): " setup_frontend
        setup_frontend=${setup_frontend:-Y}
        
        if [[ $setup_frontend =~ ^[Yy]$ ]]; then
            echo ""
            echo "========================================
  前端环境配置
========================================"
            
            # 读取后端配置中的端口
            backend_port=5001
            if [ -f "apps/backend/.env" ]; then
                backend_port=$(grep "^FLASK_PORT=" apps/backend/.env | cut -d'=' -f2)
                backend_port=${backend_port:-5001}
            fi
            
            # 询问是否远程访问
            read -p "是否需要远程访问配置? (y/N): " remote_access
            
            if [[ $remote_access =~ ^[Yy]$ ]]; then
                echo ""
                echo "请输入服务器域名或IP (例如: yourwebsite.net 或 192.168.1.100)"
                read -p "域名/IP: " server_addr
                
                echo ""
                while true; do
                    read -p "前端端口 (回车使用 5173): " frontend_port
                    frontend_port=${frontend_port:-5173}
                    if validate_port "$frontend_port"; then
                        break
                    else
                        echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                    fi
                done
                
                # 检查端口占用
                if check_port $frontend_port; then
                    echo -e "${YELLOW}⚠️  端口 $frontend_port 已被占用${NC}"
                    available_port=$(get_available_port $frontend_port)
                    if [ "$available_port" != "0" ]; then
                        read -p "使用可用端口 $available_port ? (Y/n): " use_available
                        if [[ ! $use_available =~ ^[Nn]$ ]]; then
                            frontend_port=$available_port
                        else
                            while true; do
                                read -p "请输入其他端口: " frontend_port
                                if validate_port "$frontend_port"; then
                                    break
                                else
                                    echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                                fi
                            done
                        fi
                    else
                        while true; do
                            read -p "请输入其他端口: " frontend_port
                            if validate_port "$frontend_port"; then
                                break
                            else
                                echo -e "${RED}错误: 请输入有效的端口号 (1-65535)${NC}"
                            fi
                        done
                    fi
                fi
                
                echo ""
                echo "选择协议:"
                echo "  1. HTTP"
                echo "  2. HTTPS"
                read -p "选择 (1-2) [1]: " protocol_choice
                if [ "$protocol_choice" = "2" ]; then
                    protocol="https"
                else
                    protocol="http"
                fi
                
                API_URL="${protocol}://${server_addr}:${backend_port}"
            else
                # 本地开发模式
                frontend_port=5173
                
                # 检查端口占用
                if check_port $frontend_port; then
                    echo -e "${YELLOW}⚠️  前端端口 $frontend_port 已被占用${NC}"
                    available_port=$(get_available_port $frontend_port)
                    if [ "$available_port" != "0" ] && [ "$available_port" != "$frontend_port" ]; then
                        echo "将使用可用端口: $available_port"
                        frontend_port=$available_port
                    fi
                fi
                
                API_URL="http://localhost:${backend_port}"
            fi
            
            # 创建前端 .env
            if [[ $remote_access =~ ^[Yy]$ ]]; then
                # 远程访问：使用域名白名单
                cat > apps/frontend/.env << EOF
# Feng Admin 前端环境配置
# 配置生成于 $(date)

VITE_API_BASE_URL=${API_URL}
VITE_APP_TITLE=Feng Admin
VITE_APP_VERSION=1.0.0
VITE_ENABLE_DEV_TOOLS=true
VITE_ENABLE_LOGGING=true
VITE_SERVER_HOST=0.0.0.0
VITE_SERVER_PORT=${frontend_port}
# 远程访问模式：仅允许配置的域名
VITE_ALLOWED_HOSTS=${server_addr}
EOF
                # 设置前端.env文件权限
                set_env_permissions "apps/frontend/.env"
            else
                # 本地开发：允许所有主机
                cat > apps/frontend/.env << EOF
# Feng Admin 前端环境配置
# 配置生成于 $(date)

VITE_API_BASE_URL=${API_URL}
VITE_APP_TITLE=Feng Admin
VITE_APP_VERSION=1.0.0
VITE_ENABLE_DEV_TOOLS=true
VITE_ENABLE_LOGGING=true
VITE_SERVER_HOST=0.0.0.0
VITE_SERVER_PORT=${frontend_port}
# 本地开发模式：允许所有主机访问
VITE_ALLOW_ALL_HOSTS=true
EOF
                # 设置前端.env文件权限
                set_env_permissions "apps/frontend/.env"
            fi
            
            echo -e "${GREEN}✓ 前端配置已创建${NC}"
            
            if [[ $remote_access =~ ^[Yy]$ ]]; then
                echo ""
                echo -e "${BLUE}配置信息:${NC}"
                echo -e "  服务器地址: ${CYAN}${server_addr}${NC}"
                echo -e "  后端: ${CYAN}${protocol}://${server_addr}:${backend_port}${NC}"
                echo -e "  前端: ${CYAN}${protocol}://${server_addr}:${frontend_port}${NC}"
                echo -e "  ${GREEN}✓ 已配置域名白名单，仅允许 ${server_addr} 访问${NC}"
            fi
        else
            echo -e "${YELLOW}跳过前端配置 (将使用默认值)${NC}"
        fi
    fi
else
    echo -e "${GREEN}✓ 前端环境配置已就绪${NC}"
fi

echo ""

# 选择启动模式
echo -e "${YELLOW}请选择启动模式:${NC}"
echo "  1. 同时启动前端和后端 (推荐)"
echo "  2. 仅启动后端"
echo "  3. 仅启动前端"
echo ""
read -p "请输入选项 (1-3): " choice

case $choice in
    1)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  启动模式: 前端 + 后端${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        # 检查后端端口占用
        BACKEND_PORT=5001
        if [ -f "apps/backend/.env" ]; then
            BACKEND_PORT=$(grep "^FLASK_PORT=" apps/backend/.env | cut -d'=' -f2)
            BACKEND_PORT=${BACKEND_PORT:-5001}
        fi
        
        if check_port $BACKEND_PORT; then
            echo -e "${RED}========================================${NC}"
            echo -e "${RED}  错误: 后端端口被占用${NC}"
            echo -e "${RED}========================================${NC}"
            echo ""
            echo -e "${YELLOW}端口 ${BACKEND_PORT} 已被占用。${NC}"
            echo ""
            echo "解决方案:"
            echo "  1. 停止占用端口的进程:"
            echo "     lsof -ti:${BACKEND_PORT} | xargs kill -9"
            echo ""
            echo "  2. 或者重新配置使用其他端口:"
            echo "     删除 apps/backend/.env 文件，重新运行此脚本"
            echo ""
            exit 1
        fi
        
        # 启动后端
        echo -e "${GREEN}[1/2] 启动后端服务...${NC}"
        if ! safe_cd apps/backend; then
            exit 1
        fi
        chmod +x start.sh
        ./start.sh &
        BACKEND_PID=$!
        if ! safe_cd ../..; then
            exit 1
        fi
        
        # 等待2秒
        sleep 2
        
        # 启动前端
        echo ""
        echo -e "${GREEN}[2/2] 启动前端服务...${NC}"
        if ! safe_cd apps/frontend; then
            exit 1
        fi
        chmod +x start.sh
        ./start.sh &
        FRONTEND_PID=$!
        if ! safe_cd ../..; then
            exit 1
        fi
        
        # 等待服务启动
        sleep 3
        
        echo ""
        echo -e "${GREEN}========================================${NC}"
        echo -e "${GREEN}  服务启动成功！${NC}"
        echo -e "${GREEN}========================================${NC}"
        echo ""
        
        # 读取配置文件获取实际地址
        BACKEND_PORT=5001
        FRONTEND_PORT=5173
        BACKEND_API_URL=""
        FRONTEND_URL=""
        
        if [ -f "apps/backend/.env" ]; then
            BACKEND_PORT=$(grep "^FLASK_PORT=" apps/backend/.env | cut -d'=' -f2)
            BACKEND_PORT=${BACKEND_PORT:-5001}
            
            CORS_ORIGINS=$(grep "^CORS_ORIGINS=" apps/backend/.env | cut -d'=' -f2)
            if [ -n "$CORS_ORIGINS" ] && [ "$CORS_ORIGINS" != "*" ]; then
                FRONTEND_URL="$CORS_ORIGINS"
            fi
        fi
        
        if [ -f "apps/frontend/.env" ]; then
            FRONTEND_PORT=$(grep "^VITE_SERVER_PORT=" apps/frontend/.env | cut -d'=' -f2)
            FRONTEND_PORT=${FRONTEND_PORT:-5173}
            
            BACKEND_API_URL=$(grep "^VITE_API_BASE_URL=" apps/frontend/.env | cut -d'=' -f2)
        fi
        
        # 显示访问地址
        if [ -n "$BACKEND_API_URL" ] && [[ ! "$BACKEND_API_URL" =~ localhost ]]; then
            # 远程访问配置
            echo -e "${BLUE}访问地址:${NC}"
            echo -e "  前端: ${CYAN}${FRONTEND_URL:-http://localhost:${FRONTEND_PORT}}${NC}"
            echo -e "  后端: ${CYAN}${BACKEND_API_URL}${NC}"
            echo ""
            echo -e "${BLUE}本地访问:${NC}"
            echo -e "  前端: ${BLUE}http://localhost:${FRONTEND_PORT}${NC}"
            echo -e "  后端: ${BLUE}http://localhost:${BACKEND_PORT}${NC}"
        else
            # 本地开发配置
            echo -e "${BLUE}本地访问:${NC}"
            echo -e "  前端: ${BLUE}http://localhost:${FRONTEND_PORT}${NC}"
            echo -e "  后端: ${BLUE}http://localhost:${BACKEND_PORT}${NC}"
            echo ""
            echo -e "${BLUE}远程访问:${NC}"
            echo -e "  前端: ${BLUE}http://YOUR_IP:${FRONTEND_PORT}${NC}"
            echo -e "  后端: ${BLUE}http://YOUR_IP:${BACKEND_PORT}${NC}"
            echo -e "  (将 YOUR_IP 替换为服务器IP地址，使用 'ifconfig' 或 'ip addr' 查看)"
        fi
        
        echo ""
        echo -e "${YELLOW}提示:${NC}"
        echo "  - 按 Ctrl+C 停止所有服务"
        if [ -n "$BACKEND_API_URL" ] && [[ ! "$BACKEND_API_URL" =~ localhost ]]; then
            echo "  - 请确保防火墙已开放端口 ${BACKEND_PORT} 和 ${FRONTEND_PORT}"
            echo "  - 如使用域名，请确保已正确配置 DNS 解析"
        fi
        echo ""
        
        # 清理函数
        cleanup() {
            echo ''
            echo -e "${YELLOW}正在停止服务...${NC}"
            
            # 终止后端进程组（包括所有子进程）
            if [ -n "$BACKEND_PID" ]; then
                echo "停止后端服务..."
                # 首先尝试优雅地终止子进程
                pkill -P $BACKEND_PID 2>/dev/null
                # 等待1秒
                sleep 1
                # 终止主进程
                kill $BACKEND_PID 2>/dev/null || true
                # 再等待1秒，如果还存在才强制终止
                sleep 1
                if kill -0 $BACKEND_PID 2>/dev/null; then
                    kill -9 $BACKEND_PID 2>/dev/null || true
                fi
            fi
            
            # 终止前端进程组
            if [ -n "$FRONTEND_PID" ]; then
                echo "停止前端服务..."
                # 首先尝试优雅地终止子进程
                pkill -P $FRONTEND_PID 2>/dev/null
                # 等待1秒
                sleep 1
                # 终止主进程
                kill $FRONTEND_PID 2>/dev/null || true
                # 再等待1秒，如果还存在才强制终止
                sleep 1
                if kill -0 $FRONTEND_PID 2>/dev/null; then
                    kill -9 $FRONTEND_PID 2>/dev/null || true
                fi
            fi
            
            echo -e "${GREEN}服务已停止${NC}"
            exit 0
        }
        
        # 等待用户中断
        trap cleanup INT TERM
        wait
        ;;
        
    2)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  启动模式: 仅后端${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        # 检查后端端口占用
        BACKEND_PORT=5001
        if [ -f "apps/backend/.env" ]; then
            BACKEND_PORT=$(grep "^FLASK_PORT=" apps/backend/.env | cut -d'=' -f2)
            BACKEND_PORT=${BACKEND_PORT:-5001}
        fi
        
        if check_port $BACKEND_PORT; then
            echo -e "${RED}错误: 端口 ${BACKEND_PORT} 已被占用${NC}"
            echo ""
            echo "解决方案:"
            echo "  1. 停止占用端口的进程: lsof -ti:${BACKEND_PORT} | xargs kill -9"
            echo "  2. 或重新配置: 删除 apps/backend/.env 文件并重新运行"
            echo ""
            exit 1
        fi
        
        if ! safe_cd apps/backend; then
            exit 1
        fi
        chmod +x start.sh
        ./start.sh
        ;;
        
    3)
        echo ""
        echo -e "${BLUE}========================================${NC}"
        echo -e "${BLUE}  启动模式: 仅前端${NC}"
        echo -e "${BLUE}========================================${NC}"
        echo ""
        
        if ! safe_cd apps/frontend; then
            exit 1
        fi
        chmod +x start.sh
        ./start.sh
        ;;
        
    *)
        echo ""
        echo -e "${RED}无效的选项${NC}"
        read -p "按回车键退出..."
        exit 1
        ;;
esac

